package main


import(
	"encoding/json"
	"fmt"
	"time"
	"github.com/hyperledger/fabric-contract-api-go/contractapi"
)


PutState(key string, value []byte) error  //储存管理接口


type Order struct{  //订单结构体
	OrderID string  json:"OrderID"  // 订单(交易) ID
    UserID string  json:"UserID"  // 用户 ID
	Price float64  json:"price"  //订单价格
	Quantity float64  json:"Quantity"  //订单数量
	isBuy bool  //是否为买方
	submitTime time.time  //交易提交时间
}


type Clearing struct{  //交易清算结构体
	Price float64  json:"price"  //成交价格
	Quantity float64  json:"Quantity"  //成交数量
	isBuy bool  //是否为买方交易
	ClearTime time.time  //清算时间
}


func MacthOrders(buyOrders []Order, sellOrders []Order) []Order{  //匹配函数
	var Macthes []Order

	for i :=0; i < len(buyOrders); i++{
		for j :=0; j < len(sellOrders); j++{
			if  buyOrders[i].price >= sellOrders[j].price && buyOrders[i].Quantity > 0 && sellOrders[j].Quantity > 0 {   //判断订单是否匹配
				
				qty := min(buyOrders[i].Quantity, sellOrders[j].Quantity)  //计算交易数量

				match := Order{   
					price: sellOrders[j].Price,
					Quantity: qty,
					IsBuy: buyOrders[i].IsBuy,


					price := (buy.Price + sell.Price) / 2.0   //价格取平均值


				}   //创建匹配订单

				buyOrders[i].Quantity -= qty   

				sellOrders[j].Quantity -= qty  //更新买卖方订单的数量

				matches = append(matches,match)  //更新匹配订单结果

				saveTransaction(buyOrder.UserID, sellOrder.UserID, price, quantity)  //保存信息到账本中
			}
			
		}
	}
	return matches
	
}


//交易价格及数量的清算
func DoClearing(clearing Clearing, account map[string]float64) {
		
		
	totalCost := clearing.Cost     
	
	
	if clearing.IsBuy {     //更新买方和卖方的账户余额
		account["cash"] -= totalCost
		account["energy"] += float64(clearing.Quantity)
		
	} 
		
	else {
		account["cash"] += totalCost
		account["energy"] -= float64(clearing.Quantity)
		
	}
}

func GetOrders() ([]*Order, error) {  //调用用户数据
    resp, err := http.Get("http://172.29.19.176:5000/bidding/True")
    if err != nil {
        return nil, err

    }
    defer resp.Body.Close()

    var orders []*Order

    err = json.NewDecoder(resp.Body).Decode(&orders)
    if err != nil {
        return nil, err

    }

    return orders, nil
}


func main() {

	orders, err := getorders("http://172.29.19.176:5000/bidding/True")  //调用用户数据函数
	if err != nil {
		log.Fatal(err)
	}


	matches := MacthOrders(buyOrders, sellOrders)    //进行订单匹配

	totalCost := DoClearing(Clearing, account)   //进行清算


	inventory := make(map[string]int)

    account := settle(matches, inventory)

	fmt.Println("订单ID:" OrderID)

	for userID := range account {
        fmt.Printf("%v: %.2f\n", userID)
    }

	fmt.Println("能源剩余量：" inventory)

    fmt.Println("账户余额：" account)
	
	err = ctx.GetStub().PutState(UserID, OrderID)
	if err != nil {
		return fmt.Errorf("failed to put auction in public data: %v", err)
	}

	// set the seller of the auction as an endorser
	err = MacthOrders(buyOrders, sellOrders)
	if err != nil {
		return fmt.Errorf("failed setting state based endorsement for new organization: %v", err)
	}

	return nil
   
}



